package com.wclass.controller.sys;


import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.wclass.common.DateUtil;
import com.wclass.common.MD5Utils;
import com.wclass.common.ReturnObject;
import com.wclass.common.alibaba.SmsUtil;
import com.wclass.entity.BaseCaptcha;
import com.wclass.entity.BaseSysUser;
import com.wclass.interceptor.IgnoreAuth;
import com.wclass.service.IBaseCaptchaService;
import com.wclass.service.IBaseSysUserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author 张浩高
 * @since 2018-12-20
 */
@RestController
@RequestMapping("/sysLogin")
public class SysLoginController {

    @Autowired
    private IBaseSysUserService iBaseSysUserService;
    @Autowired
    private IBaseCaptchaService iBaseCaptchaService;

    @Value("${alibaba.accessKeyId}")
    private String accessKeyId;
    @Value("${alibaba.accessKeySecret}")
    private String accessKeySecret;
    @Value("${alibaba.signName}")
    private String signName;
    @Value("${rong.appKey}")
    private String appKey;
    @Value("${rong.appSecret}")
    private String appSecret;


    @IgnoreAuth
    @ApiOperation("获取验证码")
    @RequestMapping(value = "/getCaptcha", method = RequestMethod.GET)
    public ReturnObject getCaptcha(@ApiParam("手机号码") @RequestParam String phone,
                                   @ApiParam("密码") @RequestParam String password) throws ClientException {

        try {
            BaseSysUser userVo = iBaseSysUserService.selectOne(new EntityWrapper<BaseSysUser>().eq("phone",
                    phone));
            if (userVo != null) {
                if (MD5Utils.validate(password, userVo.getPassword())) {
                    //删除历史验证码
                    iBaseCaptchaService.delete(new EntityWrapper<BaseCaptcha>().eq("phone", phone));
                    //新建验证码
                    BaseCaptcha baseCaptcha = new BaseCaptcha(userVo.getPhone(), Integer.toString((int) ((Math
                            .random() * 9 + 1) * 1000)), DateUtil.getSomeMinute(new Date(), 10));
                    iBaseCaptchaService.insert(baseCaptcha);
                    Map<String, String> map = Maps.newHashMap();
                    map.put("code", baseCaptcha.getCaptcha());
                    //map.put("time", "10分钟");
                    return SmsUtil.sendSms(phone, "SMS_153410061", map, accessKeyId, accessKeySecret, signName);

                } else {
                    return new ReturnObject<>(1, "密码错误，请输入正确的密码！");
                }

            } else {
                return new ReturnObject<>(2, "账号不存在，请联系管理员！");
            }

        } catch (Exception e) {
            return new ReturnObject<>(12, "系统偷懒了，请联系管理员！");
        }
    }


    @IgnoreAuth
    @ApiOperation("校验验证码并登录")
    @RequestMapping(value = "/verifyCaptcha", method = RequestMethod.GET)
    public ReturnObject verifyCaptcha(@ApiParam("手机号") @RequestParam String phone,
                                      @ApiParam("验证码") @RequestParam String captcha) {
        try {
            BaseSysUser user = iBaseSysUserService.selectOne(new EntityWrapper<BaseSysUser>().eq("phone", phone));
            //删除历史验证码
            if (iBaseCaptchaService.selectCount(new EntityWrapper<BaseCaptcha>().eq("phone", phone).eq("captcha", captcha)) > 0) {
                if (iBaseCaptchaService.selectCount(new EntityWrapper<BaseCaptcha>().eq("phone", phone)
                        .eq("captcha", captcha).gt("effective_time", new Date())) > 0) {
                    return new ReturnObject(0, "登录成功", user);
                } else {
                    return new ReturnObject(1, "验证码已失效，请重新获取");
                }
            } else {
                return new ReturnObject(1, "请输入正确的验证码");
            }
        } catch (Exception e) {
            return new ReturnObject<>(12, "系统偷懒了");
        }

    }

//    @ApiOperation("登录（手机号+验证码）")
//    @IgnoreAuth
//    @RequestMapping(value = "/loginCode", method = RequestMethod.POST)
//    public ReturnObject<Object> loginCode(@ApiParam("用户名【必传】") @RequestParam String phone,
//                                          @ApiParam("设备型号") String device) {
//        try {
//            BaseSysUser userVo = iBaseSysUserService.selectOne(new EntityWrapper<BaseSysUser>().eq("phone",
//                    phone));
//            return new ReturnObject<>(0, "登录成功", userVo.getToken());
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new ReturnObject<>(12, "系统偷懒了");
//        }
//    }


    @IgnoreAuth
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    public ReturnObject<BaseSysUser> verify(@ApiParam("用户名【必传】") @RequestParam String username) {
        try {
            BaseSysUser userVo = iBaseSysUserService.selectOne(new EntityWrapper<BaseSysUser>().eq("user_name",
                    username));
            if (userVo != null) {

                return new ReturnObject<>(0, "获取用户成功", userVo);
            } else {
                return new ReturnObject<>(0, "获取用户失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject<>(12, "系统偷懒了");
        }
    }


}

